package com.wangsh.splider.orders.impl;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.service.BaseServiceImpl;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.common.util.FaceBookUtil;
import com.wangsh.splider.common.util.POIUtil;
import com.wangsh.splider.common.util.PageInfoUtil;
import com.wangsh.splider.orders.pojo.AOrdersClient;
import com.wangsh.splider.orders.pojo.AOrdersUsers;
import com.wangsh.splider.orders.pojo.AOrdersUsersEnum;
import com.wangsh.splider.orders.service.IOrdersOperService;
import com.wangsh.splider.orders.service.IOrdersDbService;
import com.wangsh.splider.system.pojo.ASysIp;
import com.wangsh.splider.system.pojo.ASysPro;
import com.wangsh.splider.system.pojo.ASysProxy;
import com.wangsh.splider.system.service.ISystemOperService;
import com.wangsh.splider.system.service.ISystemDbService;

/**
 * 订单操作的实现类
 * @author TeaBig
 */
@Service("ordersOperService")
public class OrdersOperServiceImpl extends BaseServiceImpl implements IOrdersOperService
{
	@Resource
	private IOrdersDbService ordersDbService;
	@Resource
	private ISystemOperService systemOperService;
	@Resource
	private ISystemDbService systemDbService ; 
	@Resource
	private POIUtil poiUtil;
	@Resource
	private FaceBookUtil faceBookUtil;
	
	/**
	 * 批量模拟登陆
	 */
	@Override
	public ApiResponse<Object> batchRequestHeadService()
	{
		ConstatFinalUtil.SYS_LOGGER.info("==batchRequestHeadService==");
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		
		/* 当时时间 
		 * 只更新,半个小时以前的数据
		 * */
		Calendar calendar = Calendar.getInstance() ;
		calendar.add(Calendar.MINUTE, -30);
		Date cookieStDate = calendar.getTime() ; 
		
		/* 查询所有状态为已验证的用户 */
		condMap.clear();
		condMap.put("status", AOrdersUsersEnum.STATUS_VERIFY.getStatus() + "");
		condMap.put("cookieStDate", cookieStDate);
		ApiResponse<AOrdersUsers> ordersUsersApiResponse = this.ordersDbService.findCondListUsersService(pageInfoUtil, condMap);
		for(int i = 1 ; i <= pageInfoUtil.getTotalPage() ; i ++)
		{
			/* 设置当前页 */
			pageInfoUtil.setCurrentPage(i);
			ConstatFinalUtil.SYS_LOGGER.info("正在更新Cookie,总条数:{},总页数:{},当前页:{}",pageInfoUtil.getTotalRecord(),pageInfoUtil.getTotalPage(),pageInfoUtil.getCurrentPage());
			int succedCount = 0 ; 
			int failedCount = 0 ; 
			/* 查询指定页数的数据 */
			ordersUsersApiResponse = this.ordersDbService.findCondListUsersService(pageInfoUtil, condMap);
			List<AOrdersUsers> ordersUsersList = ordersUsersApiResponse.getDataListJava() ; 
			for (Iterator iterator = ordersUsersList.iterator(); iterator.hasNext();)
			{
				AOrdersUsers ordersUsersTemp = (AOrdersUsers) iterator.next();
				
				try
				{
					/* 数据一条一条的处理 */
					ApiResponse<Object> apiResponseTarget = this.updateRequestHeadTargetService(ordersUsersTemp);
					if(apiResponseTarget.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
					{
						succedCount ++ ; 
					}else
					{
						failedCount ++ ; 
					}
				} catch (Exception e)
				{
					failedCount ++ ; 
					ConstatFinalUtil.SYS_LOGGER.error("更新Cookie失败了;usersId:{},",ordersUsersTemp.getId(),e);
				}
			}
			
			ConstatFinalUtil.SYS_LOGGER.info("更新完成;当前页:{},总条数:成功条数:{},失效条数:{}",pageInfoUtil.getCurrentPage(),ordersUsersList.size(),succedCount,failedCount);
		}
		return null ; 
	}

	/**
	 * 模拟单次登陆
	 * 		~查询请求历史中:已经访问的记录
	 * 		~用户已经在打开的页面中登陆了
	 * 		~拿着cookie看看是否可以登陆成功
	 * @param ordersUsers
	 */
	public ApiResponse<Object> updateRequestHeadTargetService(AOrdersUsers ordersUsers)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==batchRequestHeadService==id:{}",ordersUsers.getId());
		ApiResponse<Object> responseDb = new ApiResponse<Object>();
		AOrdersClient ordersClient = ordersUsers.getOrdersClient() ; 
		ASysIp sysIp = ordersUsers.getSysIp();
		/* 直接请求登陆后的服务器 */
		ASysPro sysPro = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("facebookHead") ; 
		String urlStr = sysPro.getVals(); 
		
		/* 请求头 */
		JSONObject headerJSON = new JSONObject();
		/* 方法的参数 */
		JSONObject reqJSON = new JSONObject();
		/* 设置cookie */
		/* 循环Json */
		JSONObject httpTargetJSON = ordersUsers.getHttpTargetJSON();
		JSONObject clientJSON = null;
		if(httpTargetJSON.get("request") == null)
		{
			clientJSON = new JSONObject();
		}else
		{
			clientJSON = (JSONObject) httpTargetJSON.get("request");
		}
		
		/* 设置Cookie */
		headerJSON.put("cookie", ordersUsers.getCookieTarget());
		
		headerJSON.put("ip", clientJSON.getString("ip"));
		headerJSON.put("clientIp", clientJSON.getString("clientIp"));
		
		/* 单独设置超时 */
		headerJSON.put(ConstatFinalUtil.REQ_HEADER_IGNORE + "read_timeout", 10 * 1000 + "");
		headerJSON.put(ConstatFinalUtil.REQ_HEADER_IGNORE + "req_connect_timeout", 10 * 1000 + "");
		
		reqJSON.put("header", headerJSON);
		
		/* 请求体 */
		JSONObject requestJSON = new JSONObject();
		reqJSON.put("request", requestJSON);
		
		/* 这个时候已经拿到了Cookie,不再需要设置更换ip */
		/* 设置代理 */
		//this.proxyFaceBook(ordersClient, ordersUsers);
		
		JSONObject resultJSON = this.faceBookUtil.mainAfterLogin(reqJSON);
		
		if(resultJSON != null)
		{
			JSONObject dataResultJSON = resultJSON.getJSONObject("data");
			String response = dataResultJSON.getString("response");
			JSONObject infoJSON = (JSONObject) dataResultJSON.get("infoJSON");
			/* 响应体 */
			JSONObject responseMapJSON = (JSONObject) dataResultJSON.get("responseMap");
			/* 判断一下是否登陆 */
			if(resultJSON.getString("code").equalsIgnoreCase(ApiResponseEnum.INFO_COOKIE_SUCCESS.getStatus() + ""))
			{
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_VERIFY.getStatus());
				/* 登陆失败,次数加1 */
				ordersUsers.setTotalNum(ordersUsers.getTotalNum() + 1 );
				ordersUsers.setSuccedNum(ordersUsers.getSuccedNum() + 1);
				ordersUsers.setUpdateCookieTime(new Date());
				ordersUsers.setUpdateTime(new Date());
			}else
			{
				/* 把用户登陆的地址换成我们的登陆地址 */
				response = this.facebookUpdateLogin(response,responseMapJSON);
			}
			
			if(resultJSON.getString("code").equalsIgnoreCase(ApiResponseEnum.INFO_COOKIE_SUCCESS.getStatus() + ""))
			{
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_VERIFY.getStatus());
				/* 登陆失败,次数加1 */
				ordersUsers.setTotalNum(ordersUsers.getTotalNum() + 1 );
				ordersUsers.setSuccedNum(ordersUsers.getSuccedNum() + 1);
				ordersUsers.setUpdateCookieTime(new Date());
				ordersUsers.setUpdateTime(new Date());
				/* Cookie好使 */
				ordersUsers.setUpdateCookieTime(new Date());
			}else if(resultJSON.getString("code").equalsIgnoreCase(ApiResponseEnum.INFO_COOKIE_FAILED.getStatus() + ""))
			{
				/* Cookie失效 */
				ordersUsers.setUpdateCookieTime(new Date());
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_INVALID.getStatus());
			}else
			{
				/* 把用户登陆的地址换成我们的登陆地址 */
				response = this.facebookUpdateLogin(response,responseMapJSON);
				
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_INVALID.getStatus());
				ordersUsers.setUpdateCookieTime(new Date());
			}
			
			ordersUsers.setHtmlContent(response);
			/* 获取原来存储的json信息 */
			JSONObject resultDbJSON = ordersUsers.getContentJSON() ; 
			resultDbJSON.put("code", resultJSON.getString("code"));
			resultDbJSON.put("info", resultJSON.getString("info"));
			/* 存储信息 */
			resultDbJSON.put("infoJSON", infoJSON);
			/* 获取CookieUsers的值 */
			String key = "usersId" ; 
			String usersId = dataResultJSON.getString(key);
			resultDbJSON.put(key, usersId);
			ordersUsers.setContent(resultDbJSON.toJSONString());
			
			/* 要进行更新AOrdersReq */
			responseDb = this.ordersDbService.updateOneUsersService(ordersUsers);
		}
		return responseDb ; 
	}

	/**
	 * 拿着httpSourceJSON中的信息,请求facebook
	 * 	request:是用户访问本服务的请求头
	 * 	header:本服务访问facebook的请求头
	 * 	response:facebook的响应头
	 */
	@Override
	public ApiResponse<Object> updateRequestHeadSourceService(AOrdersClient ordersClient)
	{
		ApiResponse<Object> responseDb = new ApiResponse<Object>();
		/* 直接请求登陆后的服务器 */
		ASysPro sysPro = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("facebookHead") ; 
		String urlStr = sysPro.getVals(); 
		/* 请求头 */
		JSONObject headerJSON = new JSONObject();
		/* 方法的参数 */
		JSONObject reqJSON = new JSONObject();
		/* 循环Json */
		JSONObject httpSourceJSON = ordersClient.getHttpSourceJSON();
		JSONObject clientJSON = (JSONObject) httpSourceJSON.get("request");
		String cookieReq = ordersClient.getCookieTarget() ; 
		if(cookieReq == null || "".equalsIgnoreCase(cookieReq))
		{
			cookieReq = ordersClient.getCookieClient() ;
		}
		
		/* 登陆完成 *//* 设置Cookie */
		headerJSON.put("cookie", cookieReq);
		headerJSON.put("ip", clientJSON.getString("ip"));
		headerJSON.put("clientIp", clientJSON.getString("clientIp"));
		
		reqJSON.put("header", headerJSON);
		
		/* 请求体 */
		JSONObject requestJSON = new JSONObject();
		reqJSON.put("request", requestJSON);
		
		/* 设置代理 */
		this.proxyFaceBook(ordersClient, null);
		JSONObject resultJSON = this.faceBookUtil.main(reqJSON);
		
		if(resultJSON != null)
		{
			JSONObject dataResultJSON = resultJSON.getJSONObject("data");
			String response = dataResultJSON.getString("response");
			/* 响应体 */
			JSONObject responseMapJSON = (JSONObject) dataResultJSON.get("responseMap");
			/* 网页上的数据 */
			JSONObject infoJSON = dataResultJSON.getJSONObject("infoJSON");
			
			/* 把用户登陆的地址换成我们的登陆地址 */
			response = this.facebookUpdateLogin(response,responseMapJSON);
			/* 打印返回信息 */
//		ConstatFinalUtil.SYS_LOGGER.info("ordersReqid:{},headerMap:{},paramsMap:{},response:{}",
//				ordersReq.getId(),
//				headerMap,paramsMap,response);
			httpSourceJSON.put("response", responseMapJSON);
			/* 存储header的JsonObject */
			httpSourceJSON.put("header", headerJSON);
			/* 数据 */
			httpSourceJSON.put("infoJSON", infoJSON);
			
			/* 单独处理Cookie */
			String cookieRes = dataResultJSON.getString("cookie");
			
			ordersClient.setHtmlContent(response);
			/* 只有是登陆 */
			if(ordersClient.getStatus() != AOrdersUsersEnum.STATUS_VERIFY.getStatus())
			{
				if(!cookieReq.equalsIgnoreCase(cookieRes))
				{
					/* 存储见面结果 */
					ordersClient.setCookieTarget(cookieRes);
				}
				/* 最重要的字段,只能存储登陆成功的Cookie */
				//ordersReq.setCookieFini(cookieArr.toJSONString());
				
				/* 更新信息 */
				ordersClient.setHttpSource(httpSourceJSON.toJSONString());
				responseDb = this.ordersDbService.updateOneClientService(ordersClient);
			}
		}
		return responseDb ; 
	}

	/**
	 * 修改登陆页面
	 * @return
	 */
	public String facebookUpdateLogin(String sourceHtml,JSONObject paramsJSON)
	{
		//TODO 此代码参照要参照FaceBookUtil中的info方法同步修改
		/* 登陆网址 */
		String loginUrl = "facebookSubmit.htm" ; 
		/* 获取html代码 */
		Document document = Jsoup.parse(sourceHtml);
		/* 获取表单 */
		Element loginFormEle = document.getElementById("login_form");
		if(loginFormEle != null)
		{
			/* 登陆地址 */
			String loginAction = loginFormEle.attr("action");
			paramsJSON.put("action", loginAction);
			//System.out.println("=loginAction==>" + loginAction);
			loginFormEle.attr("action", loginUrl);
		}
		/* 获取表单 */
		Element loginForm1Ele = document.getElementById("u_0_9");
		if(loginForm1Ele != null)
		{
			/* 登陆地址 */
			String loginAction = loginForm1Ele.attr("action");
			paramsJSON.put("action", loginAction);
			//System.out.println("=loginAction==>" + loginAction);
			loginForm1Ele.attr("action", loginUrl);
		}
		/* 获取表单 */
		loginForm1Ele = document.getElementById("u_0_a");
		if(loginForm1Ele != null)
		{
			/* 登陆地址 */
			String loginAction = loginForm1Ele.attr("action");
			paramsJSON.put("action", loginAction);
			//System.out.println("=loginAction==>" + loginAction);
			loginForm1Ele.attr("action", loginUrl);
		}
		
		/* 获取表单 */
		loginForm1Ele = document.getElementById("u_c_0");
		if(loginForm1Ele != null)
		{
			/* 登陆地址 */
			String loginAction = loginForm1Ele.attr("action");
			paramsJSON.put("action", loginAction);
			//System.out.println("=loginAction==>" + loginAction);
			loginForm1Ele.attr("action", loginUrl);
		}
		
		/* 获取表单 */
		loginForm1Ele = document.getElementById("u_0_c");
		if(loginForm1Ele != null)
		{
			/* 登陆地址 */
			String loginAction = loginForm1Ele.attr("action");
			paramsJSON.put("action", loginAction);
			//System.out.println("=loginAction==>" + loginAction);
			loginForm1Ele.attr("action", loginUrl);
		}
		return document.html() ; 
	}
	
	@Override
	public ApiResponse<Object> updateLoginService(AOrdersUsers ordersUsers)
	{
		ApiResponse<Object> responseDb = new ApiResponse<Object>();
		AOrdersClient ordersClient = ordersUsers.getOrdersClient() ; 
		ASysIp sysIp = ordersUsers.getSysIp();
		/* 直接请求登陆后的服务器 */
		ASysPro sysPro = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("facebookLogin") ; 
		String urlStr = sysPro.getVals(); 
		
		/* 请求头 */
		JSONObject headerJSON = new JSONObject();
		/* 方法的参数 */
		JSONObject reqJSON = new JSONObject();
		
		/* 循环Json */
		JSONObject httpSourceJSON = ordersUsers.getHttpSourceJSON();
		/* 请求登陆或者验证登陆的json */
		JSONObject httpTargetJSON = ordersUsers.getHttpTargetJSON();
		JSONObject clientJSON = (JSONObject) httpSourceJSON.get("request");
		JSONObject infoJSON = httpSourceJSON.getJSONObject("infoJSON");
		/* 获取网页上的数据 */
		JSONObject loginJSON = infoJSON.getJSONObject("login");
		String loginUrl = loginJSON.getString("action");
		
		/* 设置Cookie */
		String cookieReq = ordersUsers.getCookieTarget() ; 
		headerJSON.put("cookie", cookieReq);
		headerJSON.put("ip", clientJSON.getString("ip"));
		headerJSON.put("clientIp", clientJSON.getString("clientIp"));
		reqJSON.put("header", headerJSON);
		
		/* 请求体 */
		JSONObject requestJSON = new JSONObject();
		
		requestJSON.put("email", ordersUsers.getEmail());
		requestJSON.put("pass", ordersUsers.getPassword());
		
		/* 将登陆页相关的其它参数加上去 */
		JSONArray paramsArr = loginJSON.getJSONArray("paramsArr");
		for (Iterator iterator = paramsArr.iterator(); iterator.hasNext();)
		{
			JSONObject paramsTempJSON = (JSONObject) iterator.next();
			String name = paramsTempJSON.getString("name");
			String value = paramsTempJSON.getString("value");
			requestJSON.put(name, value);
		}
		
		reqJSON.put("request", requestJSON);
		
		/* 设置代理 */
		this.proxyFaceBook(ordersClient, ordersUsers);
		JSONObject resultJSON = this.faceBookUtil.login(loginUrl,reqJSON);
		
//		ConstatFinalUtil.SYS_LOGGER.info("ordersReqid:{},headerMap:{},paramsMap:{},response:{}",
//				ordersReq.getId(),
//				headerMap,paramsMap,"");
		if(resultJSON != null)
		{
			JSONObject dataResultJSON = resultJSON.getJSONObject("data");
			String response = dataResultJSON.getString("response");
			/* 响应体 */
			JSONObject responseMapJSON = (JSONObject) dataResultJSON.get("responseMap");
			httpTargetJSON.put("header", headerJSON);
			httpTargetJSON.put("response", responseMapJSON);
			
			/* 单独处理Cookie */
			boolean loginFlag = false ; 
			
			/* 单独处理Cookie */
			String cookieRes = dataResultJSON.getString("cookie") ;
			JSONArray cookieArr = dataResultJSON.getJSONArray("cookieArr");
			if(cookieRes != null && cookieRes.indexOf("c_user=") != -1)
			{
				if(!loginFlag)
				{
					loginFlag = true; 
				}
			}
			
			/* 把用户登陆的地址换成我们的登陆地址 */
			response = this.facebookUpdateLogin(response,responseMapJSON);
			/* 存储见面结果 */
			ordersUsers.setHtmlContent(response);
			
			httpTargetJSON.put("request", requestJSON);
			
			/* 请求登陆的json;请求json和响应信息 */
			ordersUsers.setHttpTarget(httpTargetJSON.toJSONString());
			/* 只有登陆的时候,才会修改状态 */
			if(loginFlag)
			{
				/* 登陆成功,更新Cookie */
				if(!cookieReq.equalsIgnoreCase(cookieRes))
				{
					/* 存储见面结果 */
					ordersUsers.setCookieTarget(cookieRes);
				}
				/* 说明登陆成功 */
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_LOGIN.getStatus());
				ordersUsers.setCookieTarget(cookieRes);
				ordersUsers.setCookieFini(cookieArr.toJSONString());
				
				ordersUsers.setUpdateTime(new Date());
				ordersUsers.setUpdateCookieTime(new Date());
				responseDb = this.ordersDbService.updateOneUsersService(ordersUsers);
			}else
			{
				/* 登陆失败,如果原来已经是已验证的状态,不需要更新Cookie */
				if(ordersUsers.getStatus() != AOrdersUsersEnum.STATUS_VERIFY.getStatus())
				{
					if(!cookieReq.equalsIgnoreCase(cookieRes))
					{
						/* 存储见面结果 */
						ordersUsers.setCookieTarget(cookieRes);
					}
				}
				/* 登陆失败,次数加1 */
				ordersUsers.setTotalNum(ordersUsers.getTotalNum() + 1 );
				ordersUsers.setFailedNum(ordersUsers.getFailedNum() + 1);
				ordersUsers.setUpdateTime(new Date());
				responseDb = this.ordersDbService.updateOneUsersService(ordersUsers);
//				/* 请求置顶的网页 */
//				urlStr = responseMapJSON.getString("Location");
//				if(urlStr != null && !"".equalsIgnoreCase(urlStr))
//				{
//					/* 请求Cookie指定的网址 */
//					resultJSON = this.faceBookUtil.accessUrl(responseMapJSON);
//					/* 登陆以后的网址 */
//					JSONObject dataResJSON = (JSONObject) resultJSON.get("data");
//					response = dataResJSON.getString("response");
//					/* 先更新一下登陆的相关信息 */
//					response = this.facebookUpdateLogin(response, responseMapJSON);
//					/* 存储网页内容 */
//					ordersUsers.setHtmlContent(response);
//				}
				responseDb.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
				responseDb.setInfo(ConstatFinalUtil.INFO_JSON.getString(responseDb.getCode() + ""), Collections.EMPTY_MAP);
			}
		}
		ConstatFinalUtil.SYS_LOGGER.info("facebook登陆结果:{}",responseDb.toJSON().toJSONString());
		return responseDb ; 
	}

	/**
	 * ~根据email查询AOrdersUsers
	 * ~如果查询不到,根据Cookie查询AOrdersClient
	 * ~肯定要可以根据cookie查询到AOrdersClient,同时保存AOrdersUsers
	 */
	@Override
	public ApiResponse<AOrdersUsers> operFindOneClientService(Map<String, Object> paramsMap)
	{
		ApiResponse<AOrdersUsers> apiResponse =  new ApiResponse<AOrdersUsers>();
		String cookie = paramsMap.get("cookie") + "" ;
		String email = paramsMap.get("email") + "" ;
		String pass = paramsMap.get("pass") + "" ;
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		/* 根据邮箱木有查询到
		 * 根据Cookie查询AOrdersClient */
		/* 如果Cookie重复的话,直接更新,而不是保存 */
		/* 根据Cookie查询记录 */
		condMap.clear();
		condMap.put("cookieClient", cookie);
		ApiResponse<AOrdersClient> apiResponseRes = this.ordersDbService.findOneClientService(condMap);
		AOrdersClient ordersClientRes = apiResponseRes.getDataOneJava();
		if(ordersClientRes != null)
		{
			condMap.clear();
			condMap.put("email", email);
			apiResponse = this.ordersDbService.findOneUsersService(condMap);
			AOrdersUsers ordersUsers = apiResponse.getDataOneJava();
			/* 假设用户肯定存在
			 * true:存在,更新
			 * false:不存在,要添加 */
			boolean updateFlag = true ; 
			/* 根据Cookie肯定可以查询到用户 */
			if(ordersUsers == null)
			{
				/* 如果查询到ordersClient */
				ordersUsers = new AOrdersUsers();
				ordersUsers.setSouType(AOrdersUsersEnum.SOUTYPE_LOGIN.getStatus());
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_VISTED.getStatus());
				updateFlag = false ;
			}
			/* 开始一堆的设置 */
			ordersUsers.setEmail(email);
			ordersUsers.setPhone(email);
			ordersUsers.setPassword(pass);
			ordersUsers.setClientId(ordersClientRes.getId());
			ordersUsers.setSysIpId(ordersClientRes.getSysIpId());
			ordersUsers.setSysProxyId(ordersClientRes.getSysProxyId());
			ordersUsers.setCookieTarget(ordersClientRes.getCookieTarget());
			ordersUsers.setHttpSource(ordersClientRes.getHttpSource());
			
			if(updateFlag)
			{
				/* 更新 */
				this.ordersDbService.updateOneUsersService(ordersUsers);
			}else
			{
				/* 保存 */
				ordersUsers.setPubTime(new Date());
				this.ordersDbService.saveOneUsersService(ordersUsers);
			}
			
			/* 刚存储完,重新再查询一次 */
			condMap = new HashMap<String, Object>();
			condMap.clear();
			condMap.put("email", email);
			apiResponse = this.ordersDbService.findOneUsersService(condMap);
		}
		return apiResponse;
	}
	
	/**
	 * 设置代理类
	 * ~如果原来有,就直接用原来的;
	 * ~查询当前用户属性哪一个国家
	 * ~切换ip,检查切换的ip是否正确
	 * ~使用新的ip进行登陆
	 */
	private void proxyFaceBook(AOrdersClient ordersClient,AOrdersUsers ordersUsers)
	{
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 设置代理 */
//		headerMap.put(ConstatFinalUtil.REQ_HEADER_IGNORE + "proxy", "true");
//		headerMap.put(ConstatFinalUtil.REQ_HEADER_IGNORE + "ip", "192.168.100.6");
//		headerMap.put(ConstatFinalUtil.REQ_HEADER_IGNORE + "port", "48333");
//		this.httpUtil.setProxy(headerMap);
		/* 查询当前用户属性哪一个国家
		 * 以ordersUsers为主,它要是有,就取它,要是木有,就用ordersClient
		 *  */
		String country = ""; 
		String ip = "" ; 
		ASysProxy sysProxy = null ;
		ASysIp sysIp = null ; 
		if(ordersUsers != null)
		{
			/* 说明是用户登陆 */
			if(ordersUsers.getSysProxy() != null)
			{
				/* 用户第2+次登陆,尽量使用同一个代理 */
				sysProxy = ordersUsers.getSysProxy() ; 
				sysIp = sysProxy.getSysIp() ; 
				/* 获取ip */
				ip = sysProxy.getIp();
			}else 
			{
				/* 用户第一次登陆,就使用新的ip代理 */
				sysIp = ordersUsers.getSysIp(); 
			}
		}else 
		{
			/* 说明是游客登陆 */
			/* 说明是用户登陆 */
			if(ordersClient.getSysProxy() != null)
			{
				/* 用户第2+次登陆,尽量使用同一个代理 */
				sysProxy = ordersClient.getSysProxy() ; 
				sysIp = sysProxy.getSysIp() ; 
				/* 获取ip */
				ip = sysIp.getIp();
			}else 
			{
				/* 用户第一次登陆,就使用新的ip代理 */
				sysIp = ordersClient.getSysIp(); 
			}
		}
		/* sysIp肯定有值 */
		country = sysIp.getCountry().getEngName();
		/* 根据国家,ip,端口3个完成确认 */
		condMap.clear();
		condMap.put("ip", ip);
		condMap.put("country", country);
		condMap.put("port", "80");
		sysProxy = this.systemOperService.operSaveOneSysProxy(condMap);
		/* 存储ip的结果 */
		if(ordersUsers != null)
		{
			ordersUsers.setSysProxyId(sysProxy.getId());
		}
		if(sysProxy != null)
		{
			/* 存储ip的结果 */
			ordersClient.setSysProxyId(sysProxy.getId());
			ConstatFinalUtil.SYS_LOGGER.info("切换ip结果:{}",sysProxy.getId());
		}else
		{
			ConstatFinalUtil.SYS_LOGGER.info("切换ip失败,ip:{},country:{}",ip,country);
		}
	}
	
	//读取文件并保存到数据库
	public ApiResponse<Object> batchOrdersUsersService(List<Map<String,Object>> dataList) throws IOException
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		Map<String, Object> dataOne = new HashMap<String, Object>() ; 
		apiResponse.setDataOne(dataOne);
		if(dataList.size() == 0 )
		{
			/* 说明记录已经存在,不应该再保存 */
			apiResponse.setCode(ApiResponseEnum.INFO_RECORD_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
			return apiResponse ; 
		}
		
		int totalCount = 0 ; 
		int succedCount = 0 ; 
		int failedCount = 0 ; 
		/* 获取第一行 */
		Map<String, Object> titleMap = dataList.get(0);
		for (int i = 0; i < dataList.size(); i++)
		{
			Map<String, Object> dataTempMap =dataList.get(i);
			totalCount ++; 
			
			try
			{
				AOrdersUsers ordersUsers = new AOrdersUsers();
				String ip = dataTempMap.get("ip") + "" ; 
				ip = ip.trim() ; 
				/* 存储IP */
				ApiResponse<ASysIp> apiResponseRes = this.systemOperService.operFindIp(ip);
				ASysIp sysIp = apiResponseRes.getDataOneJava() ; 
				ordersUsers.setSysIpId(sysIp.getId());
				
				String email = dataTempMap.get("账号") + "" ; 
				email = email.trim() ; 
				ordersUsers.setEmail(email);
				ordersUsers.setPhone(email);
				
				String password = dataTempMap.get("密码") + "" ; 
				password = password.trim() ; 
				ordersUsers.setPassword(password);
				
				String country = dataTempMap.get("国家代码") + "" ; 
				country = country.trim() ; 
				
				String cookieFini = dataTempMap.get("Cookie") + "" ; 
				cookieFini = cookieFini.trim() ; 
				JSONArray cookie = JSON.parseArray(cookieFini);
				StringBuffer sb = new StringBuffer();
				for (Object object : cookie)
				{
					JSONObject parseObject = JSON.parseObject(object + "");
					String name = parseObject.get("name") + "";
					String value = parseObject.get("value") + "";
					sb.append(name + "=");
					sb.append(value + ";");
				}
				ordersUsers.setCookieFini(cookieFini);
				ordersUsers.setCookieTarget(sb.toString());
				ordersUsers.setSouType(AOrdersUsersEnum.SOUTYPE_BUY.getStatus());
				ordersUsers.setStatus(AOrdersUsersEnum.STATUS_VERIFY.getStatus());
				ordersUsers.setPubTime(new Date());
				ordersUsers.setCreateTime(new Date());
				ordersUsers.setUpdateTime(new Date());
				ApiResponse<Object> apiResponseDb = this.ordersDbService.saveOneUsersService(ordersUsers);
				if(apiResponseDb.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
				{
					succedCount ++ ; 
				}else
				{
					failedCount ++ ; 
				}
			} catch (Exception e)
			{
				failedCount ++ ; 
			}
		}
		dataOne.put("totalCount", totalCount);
		dataOne.put("failedCount", failedCount);
		dataOne.put("succedCount", succedCount);
		return apiResponse ; 
	}
}
